import { defineStore } from 'pinia';
import axios from 'axios';

export const useImagingStore = defineStore('imaging', {
  state: () => ({
    images: [],
    aiReports: [],
    isLoading: false,
    error: null,
    uploadProgress: 0
  }),
  
  actions: {
    async uploadImage(formData, onUploadProgress) {
      this.isLoading = true;
      this.error = null;
      
      try {
        const response = await axios.post('/api/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: (progressEvent) => {
            if (progressEvent.total) {
              const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              this.uploadProgress = percentCompleted;
              if (onUploadProgress) {
                onUploadProgress(percentCompleted);
              }
            }
          }
        });
        this.images.push(response.data);
        return response.data;
      } catch (error) {
        this.error = error.message;
        throw error;
      } finally {
        this.isLoading = false;
        this.uploadProgress = 0;
      }
    },
    
    async fetchImages() {
      this.isLoading = true;
      this.error = null;
      
      try {
        const response = await axios.get('/api/images');
        this.images = response.data;
        return this.images;
      } catch (error) {
        this.error = error.message;
        // 使用模拟数据
        this.images = [];
        return this.images;
      } finally {
        this.isLoading = false;
      }
    },

    async fetchImagesByPatient(patientId) {
      this.isLoading = true;
      this.error = null;
      try {
        const response = await axios.get(`/api/images/patient/${patientId}`);
        return response.data;
      } catch (error) {
        this.error = error.message;
        return [];
      } finally {
        this.isLoading = false;
      }
    },
    
    async fetchAiReports(patientId = null) {
      this.isLoading = true;
      this.error = null;
      
      try {
        let url = '/api/ai-reports';
        if (patientId) {
          url = `/api/ai-reports/patient/${patientId}`;
        }
        const response = await axios.get(url);
        this.aiReports = response.data;
        return this.aiReports;
      } catch (error) {
        this.error = error.message;
        // 使用模拟数据
        this.aiReports = [];
        return this.aiReports;
      } finally {
        this.isLoading = false;
      }
    },
    
    getImageUrl(filename) {
      return `/uploads/${filename}`;
    }
  }
});